<template>
  <TableView class="table">
    <template #form>
      <NSpace justify="space-between" align="center">
        <NSpace align="center">
          接待日期选择:
          <NDatePicker input-readonly style="width: 280rem" placeholder="请选择开始时间" clearable type="daterange"
            @update-formatted-value="handleFormattedStart" />
          公务接待事由:
          <NInput v-model:value="paginationReactive.receptionContent" placeholder="请输入公务接待事由" clearable
            class="commonWidth" />
          <NButton type="primary" style="width: 78rem" ghost
            @click="() => ((paginationReactive.page = 1), getHaveDinnerList())">
            查询
          </NButton>
        </NSpace>
        <NButton type="primary" style="width: 115rem" @click="$router.push({ path: '/OA/HaveDinner/HaveDinnerAdd' })">
          接待用餐申请
        </NButton>
      </NSpace>
    </template>

    <template #table="props">
      <NDataTable v-bind="props" :bordered="false" :columns="columns" :data="tableData" :pagination="false"
        :loading="tableLoading" />
    </template>

    <template #pagination>
      <NPagination :page-sizes="paginationReactive.pageSizes" :item-count="paginationReactive.itemCount"
        :page="paginationReactive.page" :page-size="paginationReactive.pageSize"
        @update:page="paginationReactive.onChange" @update:page-size="paginationReactive.onUpdatePageSize"
        show-size-picker show-quick-jumper :suffix="() => '页'">
        <template #prefix>
          <span style="font-size: 14px;"> 共{{ paginationReactive.itemCount }}条</span>
        </template>
      </NPagination>
    </template>
  </TableView>

  <NModal :auto-focus="false" v-model:show="modalVisible" @close="modalVisible = false">
    <VDialogContent @close="modalVisible = false" @submit="recall" title="撤回提示">
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        您确定撤回该条接待申请吗？
      </div>
    </VDialogContent>
  </NModal>
</template>
<script setup lang="ts">
import {
  NSpace,
  NButton,
  NDataTable,
  NPagination,
  useMessage,
  NModal,
  NDatePicker,
  NInput
} from 'naive-ui'
import { h, reactive, ref, watch, onMounted, onDeactivated } from 'vue'
import { sendRequest } from '@/utils/api'
import { useRoute } from 'vue-router'
import type { OverTimeModel } from '@/api/overTime'
import type { HttpResponse } from '@/utils/http'
import TableView from '@/components/TableView.vue'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import router from '@/router'
import { useViewerStore } from '@/views/OA/Common/store'
import { RecordType } from '@/router/utils'
const useStore = useViewerStore()
const message = useMessage()
const route = useRoute()
const modalVisible = ref(false)

const columns: any = [
  {
    title: '申请人',
    key: 'userName',
    width: 60,
    align: useStore.isCenter
  },
  {
    title: '申请人部门',
    key: 'deptName',
    width: 100,
    align: useStore.isCenter
  },
  {
    title: '公务接待对象',
    key: 'receiver',
    width: 80,
    align: useStore.isCenter
  },
  {
    title: '接待人数',
    key: 'receptionNum',
    width: 80,
    align: useStore.isCenter
  },
  {
    title: '用餐种类',
    key: 'diningType',
    width: 80,
    align: useStore.isCenter,
    render: ({ diningType }: any) => {
      if (!diningType) return ''
      const tmp = diningType.split(',')
      const result = tmp.map((it: any) => parentCodeList.value.find((c: any) => it == c.dicCode)?.dicName)
      return result.map((it: any) => it).join('，')
    }
  },
  {
    title: '公务接待事由',
    key: 'receptionContent',
    width: 120,
    align: useStore.isCenter
  },
  {
    title: '公务接待场所',
    key: 'addressType',
    width: 120,
    align: useStore.isCenter,
    render: ({ addressType }: any) => {
      return addressType == '0' ? '馆内' : addressType == '1' ? '馆外' : ''
    }
  },
  {
    title: '公务接待日期',
    key: 'receptionTime',
    width: 80,
    align: useStore.isCenter,
    render: ({ receptionTime }: any) => {
      return receptionTime.split(' ')[0]
    }
  },
  {
    title: '申请日期',
    key: 'createTime',
    width: 80,
    align: useStore.isCenter
  },
  {
    title: '状态',
    key: 'fromStatus',
    width: 60,
    align: useStore.isCenter
  },
  {
    title: '操作',
    key: 'action',
    align: useStore.isCenter,
    width: 180,
    fixed: 'right',
    render: (row: any) => [
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          onClick: () => {
            RecordType.setRouteNameTypeFalse('A0502')
            router.push({ path: '/OA/HaveDinner/HaveDinnerInfo', query: { id: row.id } })
          }
        },
        {
          default: () => '详情'
        }
      ),
      row.fromStatusCode === 'A0605' && h(
        NButton,
        {
          type: 'info',
          quaternary: true,
          loading: row.exportLoading || false,
          onClick: () => {
            singleExport(String(row.id))
          }
        },
        {
          default: () => '导出'
        }
      ),
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          style: { display: row.fromStatus == '审批中' ? 'inlne-block' : 'none' },
          onClick: async () => {
            recallId.value = row.id
            modalVisible.value = true
          }
        },
        {
          default: () => '撤回'
        }
      ),
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          onClick: () => {
            router.push({
              path: '/OA/HaveDinner/HaveDinnerUpdate',
              query: { id: row.id, flat: true as never }
            })
          }
        },
        {
          default: () => '再次发起'
        }
      )
    ]
  }
]
//类型
const parentCodeList: any = ref([])
const getParentCode = async () => {
  const [error, res] = await sendRequest({
    module: 'progress',
    api: 'parentCode',
    override: {
      params: {
        dicCode: 'A60'
      }
    }
  })
  if (error) return
  if (res.code != 0) return
  parentCodeList.value = res.data
}
// 开始时间选择
const handleFormattedStart = (v: any) => {
  if (v) (paginationReactive.startTime = v[0]), (paginationReactive.endTime = v[1])
  else (paginationReactive.startTime = null), (paginationReactive.endTime = null)
}
// 上一页下一页
const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 0,
  startTime: null, //开始请假的开始时间
  endTime: null, //开始请假的结束时间
  receptionContent: null, //接待事由
  onChange: (page: number) => {
    paginationReactive.page = page
    getHaveDinnerList()
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    paginationReactive.page = 1
    getHaveDinnerList()
  }
})
// 撤回
const recallId = ref()
const recall = async () => {
  modalVisible.value = false
  tableLoading.value = true
  const [error, res] = await sendRequest<HttpResponse<OverTimeModel>>({
    module: 'receiveOrDispatch',
    api: 'dispatchRevoke',
    override: {
      data: {
        functionCode: 'A0533',
        resourceId: recallId.value
      }
    }
  })
  if (error) return message.error('撤回失败'), (tableLoading.value = false)
  if (res.code !== 0) return message.error('撤回失败'), (tableLoading.value = false)
  getHaveDinnerList()
  message.success('撤回成功')
}
// 获取列表
const tableData = ref([])
const tableLoading = ref(false)
const getHaveDinnerList = async () => {
  tableLoading.value = true
  const [error, res] = await sendRequest<HttpResponse<OverTimeModel>>({
    module: 'haveDinner',
    api: 'diningList',
    override: {
      params: {
        page: paginationReactive.page,
        limit: paginationReactive.pageSize,
        startTime: paginationReactive.startTime,
        endTime: paginationReactive.endTime,
        receptionContent: paginationReactive.receptionContent
      }
    }
  })
  tableLoading.value = false
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  tableData.value = []
  setTimeout(() => {
    tableData.value = res.data.list.map((t: any) => {
      return {
        ...t,
        exportLoading: false
      }
    })
    paginationReactive.itemCount = res.data.totalCount
  }, 0)
}
const singleExport = async (id: string) => {
  tableData.value.forEach((t: any) => {
    t.exportLoading = (String(t.id) === id)
  })
  const [error, res, headers] = await sendRequest<HttpResponse>({
    module: 'haveDinner',
    api: 'diningExport',
    override: {
      params: {
        id
      }
    }
  })
  if (error) {
    tableData.value.forEach((t: any) => {
      t.exportLoading = false
    })
    return message.error(error.message)
  }
  download(headers, res, '公务接待审批单')
  message.success('导出成功')
  tableData.value.forEach((t: any) => {
      t.exportLoading = false
    })
}
function download(headers: any, data: any, name?: string) {
  const val = headers['content-disposition']?.match(/(?<=filename=)(.*)/)
  let filename = val ? decodeURIComponent(val[0]) : name + '导出.xlsx'
  if (!filename.includes('xlsx')) {
    filename = filename.replace('xls', 'xlsx')
  }
  const a = document.createElement('a')
  let binaryData = []
  binaryData.push(data)
  a.href = window.URL.createObjectURL(new Blob(binaryData))
  a.download = filename
  a.click()
  window.URL.revokeObjectURL(a.href)
}
const keyUpDown = (e: any) => e.key == 'Enter' && (paginationReactive.page = 1,getHaveDinnerList())
onDeactivated(() => window.removeEventListener('keyup', keyUpDown, false))

watch(
  () => route,
  async () => {
    if (route.path == '/OA/HaveDinner/HaveDinner') {
      await getParentCode()
      getHaveDinnerList()
      window.addEventListener('keyup', keyUpDown, false)  // 回车
    }
  },
  { deep: true, immediate: true }
)
</script>
<style scoped lang="scss">
.table {
  padding: 29rem 30rem 42rem;
}
</style>
